import os
import pymongo
from datetime import datetime,timedelta
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
import base64

data_path = "/home/trasen/client/data/"
client = pymongo.MongoClient("mongodb://localhost:27017/")
login = client.admin
login.authenticate("root","trasen@321")
db = client["starsink"]
col = db["msg"]
id_col = db["msg_id"]
class MsgSave:

    @staticmethod
    def getNextValue(ID):
        ret = id_col.find_and_modify({"_id": "INC_"+ID}, {"$inc": {"INC_"+ID+"_SEQ": 1}}, safe=True, new=True)
        if ret==None:
            id_col.insert_one(({'_id': "INC_"+ID, "INC_"+ID+"_SEQ": 1}))
            new = ID + "01"
        else:
            new = ID + str(ret["INC_"+ID+"_SEQ"]).rjust(2,'0')
        return new

    @staticmethod
    def encrypt(msg):
        return msg
        #pubKey = open("pub.key",'r').read()
        #data = msg.encode("utf-8")
        #
        #recipient_key = RSA.import_key(pubKey)
        #session_key = get_random_bytes(16)
        #
        ## Encrypt the session key with the public RSA key
        #cipher_rsa = PKCS1_OAEP.new(recipient_key)
        #enc_session_key = cipher_rsa.encrypt(session_key)
        #
        ## Encrypt the data with the AES session key
        #cipher_aes = AES.new(session_key, AES.MODE_EAX)
        #ciphertext, tag = cipher_aes.encrypt_and_digest(data)

        #cipher_bytes =  b''.join([x for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext)])

        #return base64.b64encode(cipher_bytes).decode()
 

    @staticmethod
    def save(oid, msg):
        if msg["msg_type"] == "SD":
            ID = f"{oid}-EMR-{msg['msg_type']}-{msg['type_index']}-{msg['title']}-{msg['name']}-"
        if msg["msg_type"] == "PL":
            ID = f"{oid}-EMR-{msg['msg_type']}-{msg['type_index']}-{msg['title']}-T"
        if msg["msg_type"] == "DE":
            ID = f"{oid}-EMR-{msg['msg_type']}-{msg['type_index']}-{msg['title']}-T"
        msg["msg_body"] = MsgSave.encrypt(msg["msg_body"])
        new_doc = {"_id":MsgSave.getNextValue(ID), "oid":oid, "msg":msg, "create_time":datetime.now()}
        col.insert_one(new_doc)
        return (True, "消息发送成功！")
        #except:
        #    return (False, "未知错误，请联系创星！") 
